<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
        <!-- 添加文件夹选择按钮 -->
        <el-button type="success" @click="selectFolder()">选择文件夹</el-button>
        <input type="file" ref="folderInput" style="display: none" webkitdirectory @change="handleFolderSelect">
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column prop="gmtCreate" header-align="center" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="templateCode" header-align="center" align="center" label="code">
      </el-table-column>
      <el-table-column prop="templateName" header-align="center" align="center" label="模板名">
      </el-table-column>
      <el-table-column prop="templateImageUrl" header-align="center" align="center" label="预览图">
        <template slot-scope="scope">
          <div class="image-container">
            <img :src="scope.row.templateImageUrl" class="preview-image" @click="imagePreviewHandle(scope.row.templateImageUrl)"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <!-- 查看大图 -->
    <ImagePreview v-if="imagePreviewVisible" ref="imagePreview"  @refreshDataList="getDataList"></ImagePreview>

    <!-- 文件扫描结果显示 -->
    <el-dialog title="文件扫描结果" :visible.sync="scanResultVisible" width="60%">
      <el-table :data="scannedFiles" height="400" border>
        <el-table-column prop="name" label="文件名" width="200"></el-table-column>
        <el-table-column prop="path" label="路径"></el-table-column>
        <el-table-column prop="size" label="大小" width="100">
          <template slot-scope="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100"></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="processFile(scope.row)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="scanResultVisible = false">关闭</el-button>
        <el-button type="primary" @click="processAllFiles">全部处理</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './wmhGalaxyTemplate-add-or-update'
import ImagePreview from '@/views/common/image-preview'
export default {
  data() {
    return {
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      imagePreviewVisible: false,
      // 添加文件扫描相关数据
      scanResultVisible: false,
      scannedFiles: [],
    }
  },
  components: {
    AddOrUpdate,
    ImagePreview
  },
  activated() {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/template/template/queryWormholeGalaxyTemplateList'),
          method: 'post',
          data: this.$http.adornData({
            isPage: true,
            pageNumb: this.pageIndex,
            pageSize: this.pageSize,
          })
      }).then(({ data }) => {
        if (data && data.success) {
          this.dataList = data.data
          this.totalPage = data.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 查看大图
    imagePreviewHandle(url){
      this.imagePreviewVisible = true
      this.$nextTick(() => {
        this.$refs.imagePreview.init(url)
      })
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle(id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/template/template/deleteWormholeGalaxyTemplate'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 添加文件夹选择功能
    selectFolder() {
      this.$refs.folderInput.click();
    },
    // 处理文件夹选择
    handleFolderSelect(event) {
      const files = event.target.files;
      if (files.length > 0) {
        this.scanFolder(files);
      }
      // 重置input值，允许选择相同文件夹
      event.target.value = '';
    },
    // 扫描文件夹
    scanFolder(files) {
      this.scannedFiles = [];

      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const filePath = file.webkitRelativePath || file.name;

        // 打印每个被扫描的文件名
        console.log('Scanned file:', file.name);
        console.log('File path:', filePath);

        this.scannedFiles.push({
          name: file.name,
          path: filePath,
          size: file.size,
          type: file.type || this.getFileType(file.name),
          file: file
        });
      }

      // 打印扫描结果汇总
      console.log('Total files scanned:', this.scannedFiles.length);
      console.log('Scanned files list:', this.scannedFiles);

      this.scanResultVisible = true;
    },
    // 获取文件类型
    getFileType(filename) {
      const extension = filename.split('.').pop().toLowerCase();
      const typeMap = {
        'jpg': 'image',
        'jpeg': 'image',
        'png': 'image',
        'gif': 'image',
        'bmp': 'image',
        'txt': 'text',
        'pdf': 'pdf',
        'doc': 'document',
        'docx': 'document',
        'xls': 'spreadsheet',
        'xlsx': 'spreadsheet'
      };
      return typeMap[extension] || 'unknown';
    },
    // 格式化文件大小
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 处理单个文件
    processFile(fileInfo) {
      console.log('处理文件:', fileInfo);
      this.$message({
        message: `正在处理文件: ${fileInfo.name}`,
        type: 'info',
        duration: 1500
      });

      // 这里可以添加具体的文件处理逻辑
      // 例如：上传到服务器、预览、转换等
      // 根据文件类型进行不同的处理
      if (fileInfo.type === 'image') {
        this.handleImageFile(fileInfo);
      } else {
        this.handleOtherFile(fileInfo);
      }
    },
    // 处理图像文件
    handleImageFile(fileInfo) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // 可以在这里处理图像数据
        console.log('图像文件已加载:', fileInfo.name);
        this.$message({
          message: `图像文件 ${fileInfo.name} 已加载`,
          type: 'success',
          duration: 1500
        });
      };
      reader.readAsDataURL(fileInfo.file);
    },
    // 处理其他类型文件
    handleOtherFile(fileInfo) {
      console.log('处理非图像文件:', fileInfo.name);
      this.$message({
        message: `已处理文件: ${fileInfo.name}`,
        type: 'success',
        duration: 1500
      });
    },
    // 处理所有文件
    processAllFiles() {
      this.scannedFiles.forEach(fileInfo => {
        this.processFile(fileInfo);
      });
      this.$message({
        message: '所有文件已开始处理',
        type: 'success',
        duration: 1500
      });
    }
  }
}
</script>

<style scoped>
.mod-config {
  padding: 20px;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 150px;
  padding: 10px 0;
}

.preview-image {
  width: 120px;
  height: 120px;
  cursor: pointer;
  object-fit: contain;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 8px;
  background-color: #f8f9fa;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: block;
  margin: 0 auto;
}

.preview-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: #ffffff;
  border-color: #409EFF;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .image-container {
    min-height: 100px;
  }

  .preview-image {
    width: 80px;
    height: 80px;
  }
}
</style>
